package ZuoChengYun.P4;

import java.util.Arrays;

/**
 *
 * (1) 归并排序
 * 归并排序采用分而治之的策略，主要是进行递归调用的方式进行的
 * @author Knife
 */
public class SmallSum {
    public static void main(String[] args) {
        int [] arr = new int[]{7,5,8,4,6,2,9,3};
        int [] temp = new int[arr.length];
        partition(arr,0,arr.length-1,temp);
        System.out.println("进行排序过得数组为："+Arrays.toString(arr));
    }

    public static void partition(int [] arr,int left,int right,int [] temp){
        int mid = (left+right)/2;
        if (left<right){
            partition(arr,left,mid,temp);
            partition(arr,mid+1,right,temp);
            merge(arr,left,mid,right,temp);
        }

    }

    public static void merge(int [] arr,int left,int mid,int right,int [] temp){
        int i = left;
        int j = mid+1;
        int t = 0;
        // todo : 将两个数组进行合并
        while (i<=mid && j<=right){
            if (arr[i] < arr[j]){
                temp[t] = arr[i++];
            } else {
                temp[t] = arr[j++];
            }
            t++;
        }
        // todo : 剩余的数组进行合并
        while (i<=mid){
            temp[t++] = arr[i++];
        }
        while (j<=right){
            temp[t++] = arr[j++];
        }

        int n = 0;
        int tempIndex = left;
        while (tempIndex <= right){
            arr[tempIndex++] = temp[n++];
        }
    }
}
